package com.erp.pro.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.erp.common.controller.BaseController;
import com.erp.common.utils.*;
import com.erp.itm.domain.DeviceAmountTwoDO;
import com.erp.itm.domain.ProjectDO;
import com.erp.itm.domain.ProjectLogDO;
import com.erp.itm.service.DeviceAmountTwoService;
import com.erp.itm.service.ProjectLogService;
import com.erp.itm.service.ProjectService;
import com.erp.pro.domain.InstockDO;
import com.erp.pro.domain.ProductDO;
import com.erp.pro.service.InstockService;
import com.erp.pro.service.ProductQtyService;
import com.erp.pro.service.ProductService;
import com.erp.pur.domain.GroupDO;
import com.erp.pur.domain.GroupDetialDO;
import com.erp.pur.service.GroupDetialService;
import com.erp.pur.service.GroupService;
import com.erp.system.domain.UserDO;
import org.apache.catalina.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.erp.pro.domain.OutstockDO;
import com.erp.pro.service.OutstockService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 
 * @author Eric
 * @email shiliang900713@163.com
 * @date 2019-10-08 14:39:46
 */
 
@Controller
@RequestMapping("/pro/outstock")
public class OutstockController extends BaseController {
	@Autowired
	private OutstockService outstockService;

	@Autowired
	private InstockService instockService;

	@Autowired
	private DeviceAmountTwoService deviceAmountTwoService;

	@Autowired
	private ProjectLogService projectLogService;

	@Autowired
	private ProductService productService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private ProductQtyService productQtyService;

	@Autowired
	private GroupService groupService;

	@GetMapping()
	@RequiresPermissions("pro:outstock:outstock")
	String Outstock(){
	    return "pro/outstock/outstock";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("pro:outstock:outstock")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<OutstockDO> outstockList = outstockService.list(query);
		int total = outstockService.count(query);
		PageUtils pageUtils = new PageUtils(outstockList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("pro:outstock:add")
	String add(){
	    return "pro/outstock/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("pro:outstock:edit")
	String edit(@PathVariable("id") Long id,Model model){
		OutstockDO outstock = outstockService.get(id);
		//查询当前信息
		InstockDO instockDO = instockService.get(outstock.getInId());
		model.addAttribute("instockDO", instockDO);
		if(instockDO.getOutQty() == null){
			instockDO.setOutQty(0);
		}
		int newoutQty = instockDO.getInqty()-instockDO.getOutQty();
		outstock.setNewoutQty(newoutQty);
		model.addAttribute("outstock", outstock);
		//查询批次基本信息
		List<InstockDO> instockDOList = instockService.findByOutQty(outstock.getSkuid());
		model.addAttribute("instockDOList", instockDOList);
		List<ProjectDO> projectDOList = projectService.list(null);
		model.addAttribute("projectDOList", projectDOList);
	    return "pro/outstock/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("pro:outstock:add")
	public R save( OutstockDO outstock){
		outstock.setUserNameCreate(getUsername());
		outstock.setUserIdCreate(getUserId());
		outstock.setGmtCreate(new Date());

		if(outstock.getPeojiectId() != null){
			ProjectDO projectDO = projectService.get(outstock.getPeojiectId());
			outstock.setPeojiectNumber(projectDO.getItmNumber());
		}
		outstock.setStatus(1);
		if(outstockService.save(outstock)>0){
			return R.ok("添加出库信息成功");
		}
		return R.error("添加出库信息失败");
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("pro:outstock:edit")
	public R update( OutstockDO outstock){

		if(outstock.getPeojiectId() != null){
			ProjectDO projectDO = projectService.get(outstock.getPeojiectId());
			outstock.setPeojiectNumber(projectDO.getItmNumber());
		}
		outstockService.update(outstock);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("pro:outstock:remove")
	public R remove( Long id){
		if(outstockService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}


	/**
	 * 确认出库
	 */
	@PostMapping( "/confirmStock")
	@ResponseBody
	public R confirmStock( Long id){
		UserDO userDO = ShiroUtils.getUser();
		//修改采购流程中的出库数量
		OutstockDO outstockDO = outstockService.get(id);
		//修改入库记录中的出库数量
		InstockDO instockDO= new InstockDO();
		instockDO.setId(outstockDO.getInId());
		instockDO.setOutQty(outstockDO.getOutQty());
		int i = instockService.update(instockDO);
		if(i>0){
			//修改项目中的采购成本（公司采购  现场采购 其他采购）
			DeviceAmountTwoDO deviceAmountTwoDO = deviceAmountTwoService.getProjectId(outstockDO.getPeojiectId());
			String message ="";
			BigDecimal outqty = new BigDecimal(outstockDO.getOutQty().toString());
			if(deviceAmountTwoDO != null){
				message= "修改公司采购价格："+deviceAmountTwoDO.getCompPurPrice()+"为："+(outstockDO.getPurPrice().multiply(outqty));
				deviceAmountTwoDO.setCompPurPrice(outstockDO.getPurPrice().multiply(outqty));
				deviceAmountTwoService.update(deviceAmountTwoDO);
			}else{
				deviceAmountTwoDO = new DeviceAmountTwoDO();
				deviceAmountTwoDO.setCompPurPrice(outstockDO.getPurPrice().multiply(outqty));
				deviceAmountTwoDO.setProjectId(outstockDO.getPeojiectId());
				deviceAmountTwoService.save(deviceAmountTwoDO);
				message= "新增公司采购价格："+outstockDO.getPurPrice().multiply(outqty);
			}
			ProjectLogDO projectLogDO = new ProjectLogDO();
			projectLogDO.setGmtCreate(new Date());
			projectLogDO.setProjectId(outstockDO.getPeojiectId());
			projectLogDO.setUserNameCreate(userDO.getName());
			projectLogDO.setUserIdCreate(userDO.getUserId());
			projectLogDO.setRemark(message);
			projectLogDO.setProjectName(outstockDO.getPeojiectNumber());
			projectLogService.save(projectLogDO);

			//修改采购批次出库金额
			InstockDO instockDO1 = instockService.get(outstockDO.getGroupId().intValue());
			int mmm = groupService.updateoutstockPrice(instockDO1.getPurGropupId().longValue(),outstockDO.getPurPrice().multiply(outqty));
			System.out.println(mmm);
		}
		//减库存
		productQtyService.updateBySkuInWar(outstockDO.getSkuid(),outstockDO.getOutQty(),outstockDO.getWarehouseId());//  .reduStock(outstockDO.getSkuid(),outstockDO.getOutQty());
		//计算SKU的总库存
		int allqty = productQtyService.getAllQty(outstockDO.getSkuid());
		ProductDO productDO = new ProductDO();
		productDO.setId(outstockDO.getSkuid());
		productDO.setAllQty(allqty);
		productService.update(productDO);

		//修改状态
		outstockService.confirmStock(id);
		return R.ok("出库成功");
	}


	@GetMapping("/outstockbysku/{proId}")
	String outstockbysku(@PathVariable("proId") Long proId, Model model){
		model.addAttribute("proId",proId);
		return "pro/outstock/outstockbysku";
	}


	@ResponseBody
	@GetMapping("/outstockbyskulist")
	public PageUtils outstockbyskulist(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<OutstockDO> outstockList = outstockService.list(query);
		int total = outstockService.count(query);
		PageUtils pageUtils = new PageUtils(outstockList, total);
		return pageUtils;
	}


	@PostMapping("/exportData")
	@ResponseBody
	public void downloadTemplate(OutstockDO outstockDO, HttpServletResponse response){
		//ProjectDO project
		Map<String, Object> params = new HashMap<>();
		if(StringUtils.isNotBlank(outstockDO.getPeojiectNumber())){
			params.put("peojiectNumber",outstockDO.getPeojiectNumber());
		}
		if(StringUtils.isNotBlank(outstockDO.getSkuModel())){
			params.put("skuModel",outstockDO.getSkuModel());
		}
		if(StringUtils.isNotBlank(outstockDO.getSku())){
			params.put("sku",outstockDO.getSku());
		}
		if(StringUtils.isNotBlank(outstockDO.getGroupNumber())){
			params.put("groupNumber",outstockDO.getGroupNumber());
		}
		if(StringUtils.isNotBlank(outstockDO.getWarehouseName())){
			params.put("warehouseName",outstockDO.getWarehouseName());
		}
		List<OutstockDO> outstockDOList = outstockService.list(params);
		ExcelUtil.exportExcel(outstockDOList,"出库列表","出库列表",OutstockDO.class,"出库列表.xls",response);
	}



	@GetMapping("/importexcel")
	String importexcel(){
		return "pro/outstock/importexcel";
	}


	@GetMapping("/downloadTemplate")
	@ResponseBody
	void downloadTemplate(HttpServletResponse response){
		List<OutstockDO> outstockDOList = new ArrayList<>();
		ExcelUtil.exportExcel(outstockDOList,"出库模板","出库模板",OutstockDO.class,"出库模板.xls",response);
	}


	@PostMapping("/importInfo")
	public String importInfo(@RequestParam("file") MultipartFile file) {
		System.out.println("asdasdasdasdas");
		ImportParams importParams = new ImportParams();
		// 数据处理
		importParams.setHeadRows(1);
		importParams.setTitleRows(1);
		// 需要验证
		importParams.setNeedVerfiy(false);
		try{
			ExcelImportResult<OutstockDO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), OutstockDO.class,
					importParams);
			List<OutstockDO> outstockDOList = result.getList();
			if(outstockDOList != null && outstockDOList.size()>0){
				for (OutstockDO outstock:outstockDOList) {
					if(StringUtils.isNotBlank(outstock.getSku())
							&& StringUtils.isNotBlank(outstock.getGroupNumber())
							&& outstock.getOutQty()>0){
						//查询商品信息
						ProductDO productDO = productService.getskuinfo(outstock.getSku());
						if(productDO != null){
							outstock.setSkuid(productDO.getId());
							outstock.setSkuName(productDO.getName());
							outstock.setSkuModel(productDO.getProModel());
							outstock.setSkuSpec(productDO.getProSpec());
						}else{
							System.out.println("SKU不存在");
						}
						List<InstockDO> instockDOList =  instockService.getByGroupid(outstock.getGroupNumber(),productDO.getId());
						if(instockDOList != null && instockDOList.size()>0){
							InstockDO instockDO =instockDOList.get(0);
							outstock.setInId(instockDO.getId());
							outstock.setGroupNumber(instockDO.getGroupid());
							outstock.setInQty(instockDO.getInqty());
							outstock.setNewoutQty(instockDO.getInqty()-instockDO.getOutQty());
							outstock.setPurPrice(new BigDecimal(instockDO.getPurPrice()));
							outstock.setSupplierId(Long.valueOf(instockDO.getSupplierId()));
							outstock.setSupplierName(instockDO.getSupplierName());
							outstock.setInTime(DateUtils.format(instockDO.getInqtyTime(),DateUtils.DATE_TIME_PATTERN));
							outstock.setWarehouseId(Long.valueOf(instockDO.getWarehouseId()));
							outstock.setWarehouseName(instockDO.getWarehouseName());
							outstock.setGroupId(Long.valueOf(instockDO.getPurGropupId()));

						}
						outstock.setUserNameCreate(getUsername());
						outstock.setUserIdCreate(getUserId());
						outstock.setGmtCreate(new Date());

						if(outstock.getPeojiectNumber() != null){
							Map<String, Object> map = new HashMap<>();
							map.put("itmNumber",outstock.getPeojiectNumber());
							List<ProjectDO> projectDOList = projectService.list(map);
							if(projectDOList != null && projectDOList.size()>0){
								outstock.setPeojiectId(projectDOList.get(0).getId());
								outstock.setPeojiectNumber(outstock.getPeojiectNumber());
							}
						}
						outstock.setStatus(1);
						if(outstockService.save(outstock)>0){
							System.out.println("添加出库信息成功");
						}
					}else{
						System.out.println("SKU不存在");
					}
				}
			}else{
				System.out.println("表格为空");
			}
			return "导入成功";
		}catch (IOException e) {
			System.out.println(e.getMessage());
			return "e:导入失败";
		} catch (Exception e1) {
			e1.printStackTrace();
			System.out.println(e1.getMessage());
			return "e1:导入失败";
		}
	}


}
